package org.nidy.erp.utils;

import lombok.extern.slf4j.Slf4j;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.concurrent.CompletableFuture;

@Slf4j
public class SendRequest {
    private static final HttpClient HTTP_CLIENT = HttpClient.newHttpClient();

    public static String get(String url) {
        try {
            HttpRequest request = HttpRequest.newBuilder()
                    .uri(URI.create(url))
                    .header("Content-Type", "application/json")
                    .GET()
                    .build();
            CompletableFuture<String> future = HTTP_CLIENT.sendAsync(request, HttpResponse.BodyHandlers.ofString())
                    .thenApply(response -> {
                        if (response.statusCode() == 200) {
                            log.info("GET 请求成功：Url{}", url);
                            return response.body();
                        } else {
                            log.error("GET 请求失败：Url{}, 状态码：{}", url, response.statusCode());
                            throw new RuntimeException("HTTP 状态码: " + response.statusCode());
                        }
                    }).exceptionally(e -> {
                        log.error("GET 请求异常：Url{}, 错误：{}", url, e.getMessage());
                        throw new RuntimeException("请求失败: " + e.getMessage(), e);
                    });

            return future.join();
        } catch (Exception e) {
            log.error("GET 请求发生未捕获异常：Url{}", url, e);
            return null;
        }
    }

    public static String post(String url, String jsonBody) {
        try {
            HttpRequest request = HttpRequest.newBuilder()
                    .uri(URI.create(url))
                    .header("Content-Type", "application/json")
                    .POST(HttpRequest.BodyPublishers.ofString(jsonBody))
                    .build();
            CompletableFuture<String> future = HTTP_CLIENT.sendAsync(request, HttpResponse.BodyHandlers.ofString())
                    .thenApply(response -> {
                        if (response.statusCode() == 200) {
                            log.info("POST 请求成功：Url{}", url);
                            return response.body();
                        } else {
                            log.error("POST 请求失败：Url{}, 状态码：{}", url, response.statusCode());
                            throw new RuntimeException("HTTP 状态码: " + response.statusCode());
                        }
                    }).exceptionally(e -> {
                        log.error("POST 请求异常：Url{}, 错误：{}", url, e.getMessage());
                        throw new RuntimeException("请求失败: " + e.getMessage(), e);
                    });
            return future.join();
        } catch (Exception e) {
            log.error("POST 请求发生未捕获异常：Url{}", url, e);
            return null;
        }
    }
}
